<template>
  <div class="grid grid-cols-1 gap-6">
    <!-- 最大/最小电池电压图表 -->
    <div class="border rounded p-4">
      <h4 class="text-base font-bold mb-4">Max/Min Cell Voltage</h4>
      <div ref="maxMinChartRef" style="height: 300px" class="chart"></div>
    </div>

    <!-- 电池组总电压图表 -->
    <div class="border rounded p-4">
      <h4 class="text-base font-bold mb-4">Total Voltage of Battery Pack</h4>
      <div ref="totalVoltageChartRef" style="height: 300px" class="chart"></div>
    </div>

    <!-- 电池组总电流图表 -->
    <div class="border rounded p-4">
      <h4 class="text-base font-bold mb-4">Total Current of Battery Pack</h4>
      <div ref="totalCurrentChartRef" style="height: 300px" class="chart"></div>
    </div>

    <!-- 电池组温度图表 -->
    <div class="border rounded p-4">
      <h4 class="text-base font-bold mb-4">Temperature Battery Pack</h4>
      <div ref="temperatureChartRef" style="height: 300px" class="chart"></div>
    </div>

    <!-- 电池组SOC图表 -->
    <div class="border rounded p-4">
      <h4 class="text-base font-bold mb-4">SOC</h4>
      <div ref="socChartRef" style="height: 300px" class="chart"></div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onBeforeUnmount, nextTick, watch } from "vue";
import * as echarts from "echarts/core";
import { LineChart } from "echarts/charts";
import {
  GridComponent,
  TooltipComponent,
  TitleComponent,
  LegendComponent
} from "echarts/components";
import { CanvasRenderer } from "echarts/renderers";
import { bmsApi } from "@/api/bms";
import { getToken } from "@/utils/cache";

// 注册必须的组件
echarts.use([
  CanvasRenderer,
  LineChart,
  GridComponent,
  TooltipComponent,
  TitleComponent,
  LegendComponent
]);

// Props
interface Props {
  selectedDate: Date;
  batteryPackSN: string;
}

const props = defineProps<Props>();

// 图表DOM引用
const maxMinChartRef = ref<HTMLElement | null>(null);
const totalVoltageChartRef = ref<HTMLElement | null>(null);
const totalCurrentChartRef = ref<HTMLElement | null>(null);
const temperatureChartRef = ref<HTMLElement | null>(null);
const socChartRef = ref<HTMLElement | null>(null);

// echarts实例
let maxMinChart: echarts.ECharts | null = null;
let totalVoltageChart: echarts.ECharts | null = null;
let totalCurrentChart: echarts.ECharts | null = null;
let temperatureChart: echarts.ECharts | null = null;
let socChart: echarts.ECharts | null = null;

// 共用时间轴数据
const hours = [
  "02:00",
  "06:00",
  "08:00",
  "10:00",
  "12:00",
  "14:00",
  "16:00",
  "18:00",
  "20:00",
  "20:00",
  "22:00",
  "24:00"
];

// ========== 电池电压数据 ==========
// 最大电池电压数据 - 单位: V
// 表示电池组中电压最高的单体电池电压，通常比最小电压高0.5-0.8V
const maxVoltageData = [
  0.8, 1.2, 1.5, 0.9, 2.2, 0.3, 0.4, 0.8, 1.8, 1.9, 2.2, 2.1
];

// 最小电池电压数据 - 单位: V
// 表示电池组中电压最低的单体电池电压
const minVoltageData = [
  1.5, 1.7, 2.0, 1.6, 2.7, 0.9, 0.8, 1.2, 2.2, 2.4, 2.7, 2.6
];

// ========== 电池组总电压数据 ==========
// 电池组总电压数据 - 单位: V
// 表示整个电池组的总输出电压，通常为所有单体电池电压的总和
const totalVoltageData = [
  1.2, 1.5, 1.8, 1.5, 1.7, 1.2, 2.0, 2.5, 3.0, 2.3, 2.0, 3.0
];

// ========== 电池组电流数据 ==========
// 电池组总电流数据 - 单位: A
// 表示整个电池组的输出电流，充电时为正值，放电时为负值
const totalCurrentData = [
  1.0, 0.2, 0.5, 0.3, 1.5, 2.8, 3.0, 3.2, 3.5, 2.5, 2.0, 3.0
];

// ========== 电池组温度数据 ==========
// 电池组温度数据 - 单位: °C
// 表示电池组的工作温度，正常范围通常在20-40°C之间
const temperatureData = [
  1.1, 0.0, 0.6, 0.2, 1.5, 3.0, 3.0, 2.8, 3.2, 2.5, 1.9, 3.0
];

// ========== 电池组SOC数据 ==========
// 电池荷电状态(State of Charge)数据 - 单位: %
// 表示电池剩余电量百分比，100%表示满电，0%表示没电
const socData = [1.0, 0.0, 0.5, 0.2, 1.5, 3.0, 3.0, 3.5, 2.8, 3.0, 2.0, 3.0];

// ========== 图表配置函数 ==========

// 最大/最小电压图表配置
const getMaxMinVoltageOption = () => {
  return {
    tooltip: {
      trigger: "axis"
    },
    legend: {
      data: ["Max Cell Voltage", "Min Cell Voltage"]
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: hours
    },
    yAxis: {
      type: "value",
      name: "(V)"
    },
    series: [
      {
        name: "Max Cell Voltage",
        type: "line",
        data: maxVoltageData,
        itemStyle: {
          color: "#67C23A"
        }
      },
      {
        name: "Min Cell Voltage",
        type: "line",
        data: minVoltageData,
        itemStyle: {
          color: "#409EFF"
        }
      }
    ]
  };
};

// 电池组总电压图表配置
const getTotalVoltageOption = () => {
  return {
    tooltip: {
      trigger: "axis"
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: hours
    },
    yAxis: {
      type: "value",
      name: "(V)"
    },
    series: [
      {
        type: "line",
        data: totalVoltageData,
        itemStyle: {
          color: "#E6A23C"
        },
        areaStyle: {
          opacity: 0.3
        }
      }
    ]
  };
};

// 电池组总电流图表配置
const getTotalCurrentOption = () => {
  return {
    tooltip: {
      trigger: "axis"
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: hours
    },
    yAxis: {
      type: "value",
      name: "(A)" // 电流单位
    },
    series: [
      {
        type: "line",
        data: totalCurrentData,
        itemStyle: {
          color: "#409EFF" // 蓝色
        },
        areaStyle: {
          opacity: 0.3
        }
      }
    ]
  };
};

// 电池组温度图表配置
const getTemperatureOption = () => {
  return {
    tooltip: {
      trigger: "axis"
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: hours
    },
    yAxis: {
      type: "value",
      name: "(°C)" // 温度单位
    },
    series: [
      {
        type: "line",
        data: temperatureData,
        itemStyle: {
          color: "#E6A23C" // 橙色
        },
        areaStyle: {
          opacity: 0.3
        }
      }
    ]
  };
};

// 电池组SOC图表配置
const getSocOption = () => {
  return {
    tooltip: {
      trigger: "axis"
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: hours
    },
    yAxis: {
      type: "value",
      name: "(%)" // SOC单位
    },
    series: [
      {
        type: "line",
        data: socData,
        itemStyle: {
          color: "#6366F1" // 紫色
        },
        areaStyle: {
          opacity: 0.3
        }
      }
    ]
  };
};

// 初始化图表
const initCharts = () => {
  // 初始化最大/最小电压图表
  if (maxMinChartRef.value && !maxMinChart) {
    maxMinChart = echarts.init(maxMinChartRef.value);
    maxMinChart.setOption(getMaxMinVoltageOption());
  }

  // 初始化总电压图表
  if (totalVoltageChartRef.value && !totalVoltageChart) {
    totalVoltageChart = echarts.init(totalVoltageChartRef.value);
    totalVoltageChart.setOption(getTotalVoltageOption());
  }

  // 初始化总电流图表
  if (totalCurrentChartRef.value && !totalCurrentChart) {
    totalCurrentChart = echarts.init(totalCurrentChartRef.value);
    totalCurrentChart.setOption(getTotalCurrentOption());
  }

  // 初始化温度图表
  if (temperatureChartRef.value && !temperatureChart) {
    temperatureChart = echarts.init(temperatureChartRef.value);
    temperatureChart.setOption(getTemperatureOption());
  }

  // 初始化SOC图表
  if (socChartRef.value && !socChart) {
    socChart = echarts.init(socChartRef.value);
    socChart.setOption(getSocOption());
  }
};

// 更新图表
const updateCharts = () => {
  // 更新最大/最小电压图表
  if (maxMinChart) {
    maxMinChart.setOption(getMaxMinVoltageOption());
  }

  // 更新总电压图表
  if (totalVoltageChart) {
    totalVoltageChart.setOption(getTotalVoltageOption());
  }

  // 更新总电流图表
  if (totalCurrentChart) {
    totalCurrentChart.setOption(getTotalCurrentOption());
  }

  // 更新温度图表
  if (temperatureChart) {
    temperatureChart.setOption(getTemperatureOption());
  }

  // 更新SOC图表
  if (socChart) {
    socChart.setOption(getSocOption());
  }
};

// 处理窗口大小变化
const handleResize = () => {
  // 自适应调整所有图表大小
  maxMinChart?.resize();
  totalVoltageChart?.resize();
  totalCurrentChart?.resize();
  temperatureChart?.resize();
  socChart?.resize();
};

// 获取历史数据
const fetchHistoryData = async () => {
  if (!props.batteryPackSN) return;
  
  try {
    const token = getToken?.() || "";
    const headers = { Authorization: `Bearer ${token}` };
    const data = { 
      batteryPackSN: props.batteryPackSN,
      date: props.selectedDate.toISOString().split('T')[0] // YYYY-MM-DD格式
    };
    
    const response = await bmsApi.getHistoryData(data, headers as any);
    
    if (response.code === 0 && response.data) {
      const historyData = response.data;
      
      // 更新图表数据
      if (historyData.maxVoltageData) {
        maxVoltageData.splice(0, maxVoltageData.length, ...historyData.maxVoltageData);
      }
      if (historyData.minVoltageData) {
        minVoltageData.splice(0, minVoltageData.length, ...historyData.minVoltageData);
      }
      if (historyData.totalVoltageData) {
        totalVoltageData.splice(0, totalVoltageData.length, ...historyData.totalVoltageData);
      }
      if (historyData.totalCurrentData) {
        totalCurrentData.splice(0, totalCurrentData.length, ...historyData.totalCurrentData);
      }
      if (historyData.temperatureData) {
        temperatureData.splice(0, temperatureData.length, ...historyData.temperatureData);
      }
      if (historyData.socData) {
        socData.splice(0, socData.length, ...historyData.socData);
      }
      if (historyData.hours) {
        hours.splice(0, hours.length, ...historyData.hours);
      }
      
      // 更新图表
      nextTick(() => {
        updateCharts();
      });
    }
  } catch (error) {
    console.error("获取历史数据失败:", error);
    // 保持原有模拟数据
  }
};

// 监听日期变化
watch(
  () => props.selectedDate,
  () => {
    fetchHistoryData();
  }
);

// 暴露更新图表的方法
defineExpose({
  updateCharts,
  handleResize
});

// 组件挂载
onMounted(() => {
  nextTick(() => {
    initCharts();
    // 监听窗口大小变化
    window.addEventListener("resize", handleResize);
    // 初始加载历史数据
    fetchHistoryData();
  });
});

// 销毁图表实例
onBeforeUnmount(() => {
  window.removeEventListener("resize", handleResize);

  // 释放图表实例资源
  maxMinChart?.dispose();
  maxMinChart = null;

  totalVoltageChart?.dispose();
  totalVoltageChart = null;

  totalCurrentChart?.dispose();
  totalCurrentChart = null;

  temperatureChart?.dispose();
  temperatureChart = null;

  socChart?.dispose();
  socChart = null;
});
</script>

<style scoped>
.chart {
  width: 100%;
  height: 100%;
}
</style>
